package com.vf.s.common.plugins.shiro;

import java.io.Serializable;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.session.mgt.WebSessionKey;
import com.jfinal.log.Log;

public class ShiroSessionManager extends  DefaultWebSessionManager {

	protected final Log LOG = Log.getLog(getClass());
	private static final String TOKEN = "token";
	private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";

	@Override
	protected Serializable getSessionId(ServletRequest servletRequest, ServletResponse response) {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		String sessionId =request.getHeader(TOKEN);
		if (null != sessionId && !"".equals(sessionId) && !"null".contentEquals(sessionId)) {
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
			return sessionId;
		} else {
			return super.getSessionId(request, response);
		}
	}

	@Override
	protected Session retrieveSession(SessionKey sessionKey) {
		Session session = null;
		try {
			Serializable sessionId = getSessionId(sessionKey);
			ServletRequest request = null;
			if (sessionId instanceof WebSessionKey) {
				request = ((WebSessionKey) sessionKey).getServletRequest();
			}
			if (request != null && sessionId != null) {
				return (Session) request.getAttribute(sessionId.toString());
			}
			session  = super.retrieveSession(sessionKey);
			if (request != null && sessionId != null) {
				request.setAttribute(sessionId.toString(), session);
			}
		}catch (Exception e) {
			//LOG.error("无效回话id");
		}
		return session;
	}
	
	
}
